import Vue from 'vue'
import qs from 'qs'
import axios from 'axios'
import store from '@/store'
import { VueAxios } from './axios'
import setting from '@/config/setting'
import notification from 'ant-design-vue/es/notification'
import { ACCESS_TOKEN,BUSINESS_TOKEN } from '@/store/mutation-types'

// 创建 axios 实例
const service = axios.create({
  baseURL: setting.apiBaseURL, // api base_url
  timeout: 6000, // 请求超时时间,
  crossDomain: true,
  withCredentials: false,
})

const err = (error) => {
  if (error.response) {
    const data = error.response.data
    const token = Vue.ls.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      notification.error({ message: 'Forbidden', description: data.msg})
    }
    if (error.response.status === 401) {
      notification.error({ message: 'Unauthorized', description: '请先登录' })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
  }else{
    notification.error({ message: 'network', description: '网络错误'})
  }
  return Promise.reject(error)
}
service.interceptors.request.use(config => {
  const token = Vue.ls.get(ACCESS_TOKEN)
  const business = Vue.ls.get(BUSINESS_TOKEN)
  if (token) {
    config.headers[ 'Access-Token' ] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  if(config.headers[ 'Content-Type' ] == 'multipart/form-data'){
  }else{
    config.data = (config.method === 'post' ||  config.method === 'put') ? qs.stringify(config.data) : null ;
  }
  config.headers[ 'Content-Type' ] = config.headers[ 'Content-Type' ] ? config.headers[ 'Content-Type' ] :'application/x-www-form-urlencoded';
  return config
}, err)
service.interceptors.response.use((response) => {
  if(!response.data.success){
    throw response;
  }
  return response.data
}, err)
const installer = {
  vm: {},
  install (Vue, router = {}) {
    Vue.use(VueAxios, router, service)
  }
}
export {
    installer as VueAxios,
    service as axios
}